<template>
  <div class="add-box">
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      label-width="140px"
      size="small"
      class="demo-ruleForm"
    >
      <div class="info-box">
        <IconTitle title="基础信息" imgUrl="yunwei"> </IconTitle>
        <div class="info-from">
  <el-form-item label="设备编号" prop="deviceNum">
            <el-input v-model="form.deviceNum" placeholder="请输入设备编号" />
          </el-form-item>
            <el-form-item label="设备名称" prop="deviceName">
            <el-input v-model="form.deviceName" placeholder="请输入设备名称" />
          </el-form-item>
          <el-form-item label="资产编号" prop="assetNum">
            <el-input v-model="form.assetNum" placeholder="请输入资产编号" />
          </el-form-item>
          <el-form-item label="出厂编号" prop="factoryNumber">
            <el-input v-model="form.factoryNumber" placeholder="请输入出厂编号" />
          </el-form-item>
          
        
          <el-form-item label="设备状态" prop="status">
            <el-select
              placeholder="设备状态"
              v-model="form.status"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                :key="item.id"
                v-for="item in deviceStatusSelect"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备使用状态" prop="useStatus">
            <el-select
              placeholder="设备使用状态"
              v-model="form.useStatus"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                :key="item.id"
                v-for="item in useStatusSelect"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备类别" prop="categoryId">
      
            <treeselect
              v-model="form.categoryId"
              :options="categoryList"
              :normalizer="normalizer"
            
              placeholder="请选择设备类别"
            />
          </el-form-item>
          <el-form-item label="设备品牌" prop="brandId">
            <el-select
              placeholder="设备品牌"
              v-model="form.brandId"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.brandName"
                :value="item.id"
                :key="item.id"
                v-for="item in brandList"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="负责人" prop="liableUserName" >
            <el-input v-model="form.liableUserName" @focus="selectUserDia" placeholder="请选择负责人" />
          </el-form-item>
          <el-form-item label="计划运行时间" prop="expectedRunTime">
             <el-input-number  controls-position="right"  style="width: 100%" v-model="form.expectedRunTime"   label="请输入计划运行时间(min为单位)"></el-input-number>
          </el-form-item>
           <el-form-item label="正常运行时间" prop="runTime" class='runTime'>
                           <el-input-number controls-position="right"  style="width: 50%" v-model="form.minRunTime"   label="请输入计划运行时间(min为单位)"></el-input-number>
                           <span>至</span>
                           <el-input-number controls-position="right"  style="width: 50%" v-model="form.maxRunTime"   label="请输入计划运行时间(min为单位)"></el-input-number>

          </el-form-item>
          <el-form-item label="规格型号" prop="specification">
            <el-input
              v-model="form.specification"
              placeholder="请输入规格型号"
            />
          </el-form-item>
          <el-form-item label="单位" prop="unit">
            <el-select
              placeholder="单位"
              v-model="form.unit"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.label"
                :value="item.value"
                :key="item.id"
                v-for="item in unitSelect"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="供应商" prop="supplierId">
            <el-select
              placeholder="供应商"
              v-model="form.supplierId"
              clearable
              style="width: 100%"
            >
              <el-option
                :label="item.supplierName"
                :value="item.id"
                :key="item.id"
                v-for="item in supplierList"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="购置日期" prop="purchaseDate" >
             <el-date-picker
              style="width: 100%"
      v-model="form.purchaseDate"
      type="date"
        value-format="yyyy-MM-dd"
      placeholder="选择购置日期">
    </el-date-picker>
           
    </el-date-picker>
          </el-form-item>
          <el-form-item label="购置金额" prop="purchaseAmount">
            <el-input
              v-model="form.purchaseAmount"
              placeholder="请输入购置金额"
            />
          </el-form-item>
          <el-form-item label="保修日期" prop="warrantyDate">
            <el-date-picker
              style="width: 100%"
      v-model="form.warrantyDate"
      type="date"
        value-format="yyyy-MM-dd"
      placeholder="选择保修日期">
    </el-date-picker>
            
          </el-form-item>
          <el-form-item label="投产日期" prop="introductionDate">
           
             <el-date-picker
              style="width: 100%"
      v-model="form.introductionDate"
      type="date"
       value-format="yyyy-MM-dd"
      placeholder="选择投产日期">
    </el-date-picker>
          </el-form-item>
          <el-form-item label="预计报废日期" prop="expectedScrapDate">
              <el-date-picker
              style="width: 100%"
      v-model="form.expectedScrapDate"
      type="date"
        value-format="yyyy-MM-dd"
      placeholder="选择预计报废日期">
    </el-date-picker>
           
          </el-form-item>
          <el-form-item label="电子标签码" prop="electronicLabel">
            <el-input
              v-model="form.electronicLabel"
              placeholder="请输入电子标签码"
            />
          </el-form-item>

          <el-form-item label="部门" prop="deptId">
            <treeselect
              v-model="form.deptId"
              :options="treeDeptData"
              :normalizer="normalizer"
              placeholder="请选择部门"
                @select="handleDeptChange"
            />
          </el-form-item>
          </el-form-item>

          <el-form-item label="存放位置" prop="storageLocationId">
            <treeselect
              v-model="form.storageLocationId"
              :options="storageList"
              :normalizer="normalizer"
              placeholder="请选择存放位置"
            />
          </el-form-item>
  <el-form-item label="是否管控" prop="controlOpen">
            <el-radio-group v-model="form.controlOpen">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否开启折旧" prop="depreciationOpen">
            <el-radio-group v-model="form.depreciationOpen">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="是否计量设备" prop="meteringDevice">
            <el-radio-group v-model="form.meteringDevice">
              <el-radio label="0">否</el-radio>
              <el-radio label="1">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="当前净值" prop="currentNetWorth">
            <el-input v-model="form.currentNetWorth" placeholder="请输入当前净值" />
          </el-form-item>

          <el-form-item label="理论生产节拍" prop="productionRhythm">
            <el-input
              v-model="form.productionRhythm"
              placeholder="请输入理论生产节拍"
            />
          </el-form-item>
        </div>
      </div>
      <div class="info-box">
        <IconTitle title="设备封面图片(1张)" imgUrl="yunwei"> </IconTitle>
        <div class="info-from">
          <ImageUpload
            ref="fileCoverImg"
            :fileListTem="coverImgTem"
            :limit="1"
          />
        </div>
      </div>
      <div class="info-box">
        <IconTitle title="设备图片(最多10张)" imgUrl="yunwei"> </IconTitle>
        <div class="info-from">
          <ImageUpload
            ref="fileupload"
            :fileListTem="imgArrayTem"
            :limit="10"
          />
        </div>
      </div>
      <div class="info-box">
        <IconTitle title="子设备" imgUrl="yunwei"> </IconTitle>
        <div class="info-from">12</div>
      </div>
      <div class="info-btn-box">
        <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
        <el-button @click="goBack">返回</el-button>
      </div>
    </el-form>
      <SelectliableUser
      ref="selectLiable"
      v-if="selectLiableDia"
      :changeidentityDia.sync="selectLiableDia"
      @closeSelect='selectUser'
    ></SelectliableUser>
  </div>
</template>
<script>
import IconTitle from "@/components/icon-title/index.vue";
import ImageUpload from "@/components/ImageUpload/index.vue";
import SelectliableUser from "@/views/ems/equipment/components/selectliableUser.vue";
import {
  getSelectUseStatus,
  getSelectDeviceStatus,
  getSelectUnit,
  addObj,
  getObj,
  putObj,
} from "@/api/ems/equipment/account";
import { fetchListTree } from "@/api/ems/equipment/category";
import { fetchPositionListTree } from "@/api/ems/equipment/position";
import { getBrandList } from "@/api/ems/equipment/brand";
import { getList } from "@/api/ems/equipment/supplier";
import { fetchTree } from "@/api/admin/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  name: "AddIndex",
  components: {
    IconTitle,
    Treeselect,
    ImageUpload,
    SelectliableUser,
  },
  props: {
    id: {
      type: Number,
    },
  },
  data() {
    return {
      useStatusSelect: [], //使用状态
      deviceStatusSelect: [], //设备状态
      unitSelect: [], //单位
      categoryList: [], //设备类别
      storageList: [], //存放位置
      brandList: [], //和设备品牌
      supplierList: [], //供应商
      treeDeptData: [], //部门
      form: {
        id: null,
        deviceNum: null,
        assetNum: null,
        factoryNumber: null,
        deviceName: null,
        status: null,
        useStatus: null,
        categoryId: null,
        brandId: null,
        liableUserId: null,
        liableUserName: null,
        expectedRunTime: null,
        specification: null,
        unit: null,
        supplierId: null,
        purchaseDate: null,
        purchaseAmount: null,
        warrantyDate: null,
        introductionDate: null,
        expectedScrapDate: null,
        electronicLabel: null,
        deptName: null,
        deptId: null,
        storageLocationId: null,
        currentNetWorth: null,
        productionRhythm: null,
        coverImgId: "",
        imgIdArray: [],
        expectedRunTime: 0,
        minRunTime: 0,
        maxRunTime: 0,
        depreciationOpen: "0",
        controlOpen: "0",
        meteringDevice: "0",
      },
      coverImgTem: [],
      imgArrayTem: [],
      rules: {
        deviceNum: [
          { required: true, message: "请输入设备编号", trigger: "blur" },
        ],
        deviceName: [
          { required: true, message: "请输入设备名称", trigger: "blur" },
        ],
         assetNum: [
          { required: true, message: "请输入资产编号", trigger: "blur" },
        ],
        factoryNumber: [
          { required: true, message: "请输入出厂编号", trigger: "blur" },
        ],
         status: [
          { required: true, message: "请选择设备状态", trigger: "change" },
        ],
         useStatus: [
          { required: true, message: "请选择设备使用状态", trigger: "change" },
        ],
        categoryId: [
          { required: false, message: "请选择设备类别", trigger: "change" },
        ],
         brandId: [
          { required: true, message: "请选择设备品牌", trigger: "change" },
        ],
         specification: [
          { required: true, message: "请输入规格型号", trigger: "blur" },
        ],
         unit: [
          { required: true, message: "请选择单位", trigger: "change" },
        ],
         supplierId: [
          { required: true, message: "请选择供应商", trigger: "change" },
        ],

         purchaseDate: [
          { required: true, message: "请选择购置日期", trigger: "change" },
        ],
         purchaseAmount: [
          { required: true, message: "请输入购置金额", trigger: "blur" },
        ],
         warrantyDate: [
          { required: true, message: "请选择保修日期", trigger: "change" },
        ],
         introductionDate: [
          { required: true, message: "请选择投产日期", trigger: "change" },
        ],
        expectedScrapDate: [
          { required: true, message: "请选择报废日期", trigger: "change" },
        ],
         electronicLabel: [
          { required: true, message: "请输入电子标签码", trigger: "blur" },
        ],
      },
      selectLiableDia: false,
    };
  },
  created() {
    this.getSelect();
  },

  mounted() {
    if (this.id > 0) {
      getObj(this.id).then((res) => {
        this.coverImgTem = [];
        this.imgArrayTem = [];
        if (!res.data.data.imgArray) {
          res.data.data.imgArray = [];
        }
        if (res.data.data.coverImg) {
          this.coverImgTem[0] = res.data.data.coverImg;
        } else {
          this.coverImgTem = [];
        }
        res.data.data.imgArray.forEach((element) => {
          this.imgArrayTem.push({
            name: element.original,
            id: element.id,
            url: element.url,
            temUrl: element.url,
          });
        });

        Object.keys(this.form).forEach((item, index) => {
          if (item !== "coverImgId" && item !== "imgIdArray") {
            this.form[item] = res.data.data[item];
          }
        });
      });
    }
  },
  methods: {
    selectUserDia() {
      this.selectLiableDia = true;
      this.$nextTick(() => {
        this.$refs.selectLiable.open();
      });
    },
    selectUser(row) {
      this.form.liableUserName = row.username;
      this.form.liableUserId = row.userId;
      this.selectLiableDia = false;
    },
    handleDeptChange(val) {
      this.form.deptName = val.name;
    },
    submitForm(formName) {
      let data = JSON.parse(JSON.stringify(this.form));
      if (this.$refs.fileCoverImg.fileList.length >= 1) {
        data.coverImgId = Number(this.$refs.fileCoverImg.fileList[0].id);
      }
      data.imgIdArray = this.$refs.fileupload.fileList.map((item) =>
        Number(item.id)
      );
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (data.id) {
            putObj(data).then((res) => {
              this.$message.success("修改成功!");
              setTimeout(() => {
                this.goBack();
              }, 1000);
            });
          } else {
            addObj(data).then((res) => {
              this.$message.success("新增成功!");
              this.reset();
            });
          }
        }else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    reset() {
      this.form = {
        id: null,
        deviceNum: null,
        assetNum: null,
        factoryNumber: null,
        deviceName: null,
        status: null,
        useStatus: null,
        categoryId: null,
        brandId: null,
        liableUserId: null,
        liableUserName: null,
        expectedRunTime: null,
        specification: null,
        unit: null,
        supplierId: null,
        purchaseDate: null,
        purchaseAmount: null,
        warrantyDate: null,
        introductionDate: null,
        expectedScrapDate: null,
        electronicLabel: null,
        deptName: null,
        deptId: null,
        storageLocationId: null,
        currentNetWorth: null,
        productionRhythm: null,
        coverImgId: "",
        imgIdArray: [],
        expectedRunTime: 0,
        minRunTime: 0,
        maxRunTime: 0,
        depreciationOpen: "0",
        controlOpen: "0",
        meteringDevice: "0",
      };
      this.coverImgTem = [];
      this.imgArrayTem = [];
      this.resetForm("form");
    },
    getSelect() {
      getSelectUseStatus().then((res) => {
        this.useStatusSelect = res.data.data;
      });
      getSelectDeviceStatus().then((res) => {
        this.deviceStatusSelect = res.data.data;
      });
      getSelectUnit().then((res) => {
        this.unitSelect = res.data.data;
      });
      fetchListTree("").then((res) => {
        this.categoryList = res.data.data ? res.data.data : [];
      });
      fetchPositionListTree("").then((res) => {
        this.storageList = res.data.data ? res.data.data : [];
      });
      getBrandList().then((res) => {
        this.brandList = res.data.data;
      });
      getList().then((res) => {
        this.supplierList = res.data.data;
      });
      //部门
      fetchTree().then((response) => {
        this.treeDeptData = response.data.data;
      });
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    goBack() {
      this.$parent.listFlag = true;
      //  this.$parent.refreshChange()
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/color.scss";
@import "@/styles/mixin.scss";
.add-box {
  margin-bottom: 50px;
  .info-box {
    background: #fff;
    border-radius: 4px;
    box-sizing: border-box;
    margin-bottom: 10px;
    padding: 10px 15px;
    overflow: hidden;
    .info-from {
      display: flex;
      flex-wrap: wrap;
      padding-top: 20px;
      position: relative;
      .el-form-item {
        width: 50%;
        padding-right: 10px;
      }
    }
    .info-from::before {
      position: absolute;
      top: 10px;
      height: 1px;
      content: "";
      left: -15px;
      right: -15px;
      display: block;
      background: #eff2f5;
    }
    .runTime {
      ::v-deep .el-form-item__content {
        display: flex;
        span {
          display: inline-block;
          margin: 0 10px;
        }
      }
    }
  }
  .info-btn-box {
    width: 100%;
    text-align: center;
  }
}
</style>